package com.ray.eye.activity;

import android.content.DialogInterface;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.widget.TextView;

import androidx.appcompat.app.AlertDialog;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.ray.base.adapter.CommonRecyclerAdapter;
import com.ray.base.adapter.ViewHolder;
import com.ray.base.base.BaseActivity;
import com.ray.base.bean.video.RecordBean;
import com.ray.base.router.RouterActivityPath;
import com.ray.base.utils.DBManager;
import com.ray.base.utils.SQLFunction;
import com.ray.base.utils.TimeUtils;
import com.ray.base.utils.ToastUtils;
import com.ray.base.viewmodel.NoViewModel;
import com.ray.eye.R;
import com.ray.eye.databinding.ActivityDownloadBinding;
import com.yanzhenjie.recyclerview.OnItemMenuClickListener;
import com.yanzhenjie.recyclerview.SwipeMenu;
import com.yanzhenjie.recyclerview.SwipeMenuBridge;
import com.yanzhenjie.recyclerview.SwipeMenuCreator;
import com.yanzhenjie.recyclerview.SwipeMenuItem;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * 观看记录
 */
@Route(path = RouterActivityPath.EyeVideo.PAGER_Download)
public class DownloadActivity extends BaseActivity<ActivityDownloadBinding, NoViewModel> implements View.OnClickListener {

    private List<RecordBean> mList = new ArrayList<>();
    private CommonRecyclerAdapter<RecordBean> adapter;
    ArrayList<HashMap<String, String>> list = new ArrayList<>();
    private static String DIR_DOWNLOAD = "Download/mydownload"; //文件路径
    @Override
    public int initContentView(Bundle savedInstanceState) {
        return R.layout.activity_download;
    }

    @Override
    protected void initData() {
        //设置监听器
        initRecyclerview();
        addData();
        initAdapter();
        binding.back.setOnClickListener(this);
        binding.cleanHistory.setOnClickListener(this);
    }

    private void initRecyclerview() {
        // 创建菜单：
        SwipeMenuCreator mSwipeMenuCreator = new SwipeMenuCreator() {

            @Override
            public void onCreateMenu(SwipeMenu leftMenu, SwipeMenu rightMenu, int position) {

                SwipeMenuItem deleteItem = new SwipeMenuItem(DownloadActivity.this)
                        .setText("删除") // 文字。
                        .setTextColor(Color.BLACK) // 文字颜色。
                        .setTextSize(20) // 文字大小。
                        .setWidth(120)
                        .setHeight(120)
                        .setBackgroundColor(Color.WHITE);
                // 各种文字和图标属性设置。
                rightMenu.addMenuItem(deleteItem); // 在Item右侧添加一个菜单。
            }
        };
        // 设置监听器。
        binding.recyclerView.setSwipeMenuCreator(mSwipeMenuCreator);

        OnItemMenuClickListener mItemMenuClickListener = new OnItemMenuClickListener() {
            @Override
            public void onItemClick(SwipeMenuBridge menuBridge, int position) {
                // 任何操作必须先关闭菜单，否则可能出现Item菜单打开状态错乱。
                menuBridge.closeMenu();

                list = SQLFunction.query(DownloadActivity.this, null, null, "download");
                if (list != null) {
                    //循环找出对应ID的视频删除
                    for (int i = 0; i < list.size(); i++) {
                        if ((list.get(i).get("id")).equals(mList.get(position).getId())) {
                            Object[] ids = {list.get(i).get("id")};
                            SQLFunction.delete(DownloadActivity.this, ids, "download");
                        }
                    }
                    mList.remove(position);
                }


                adapter.notifyItemRemoved(position);
                //如果mList里面没有数据了,则显示
                if (mList.size() == 0) {
                    binding.tvHint.setVisibility(View.VISIBLE);
                }
            }
        };
        // 菜单点击监听。
        binding.recyclerView.setOnItemMenuClickListener(mItemMenuClickListener);
    }

    private void addData() {
        list = SQLFunction.query(this, null, null, "download");
        if (list != null) {
            for (int i = list.size() - 1; i >= 0; i--) {
                RecordBean test = new RecordBean();
                Log.i("TAG", list.get(i).get("num"));
                test.setTitle(list.get(i).get("title"));
                test.setSlogan(list.get(i).get("category"));
                test.setDuration(Long.parseLong(list.get(i).get("duration")));
                test.setImage(list.get(i).get("detail"));
                test.setActionUrl(list.get(i).get("url"));
                test.setId(list.get(i).get("id"));
                test.setDesc(list.get(i).get("description"));
                mList.add(test);
            }
        } else {
            Log.i("TAG:", "从数据库中没有拿到数据！");
        }
        //如果mList里面没有数据了,则显示
        if (mList.size() == 0) {
            binding.tvHint.setVisibility(View.VISIBLE);
        }
    }

    private void initAdapter() {
        if (mList != null) {
            if (adapter == null) {
                adapter = new CommonRecyclerAdapter<RecordBean>(this, mList, R.layout.item_video_bean_for_client) {
                    @Override
                    public void convert(ViewHolder holder, RecordBean item, int position) {
                        holder.setImageByGlide(R.id.detail, item.getImage());
                        holder.setText(R.id.title, item.getTitle());
                        holder.setText(R.id.slogan, "#" + item.getSlogan());
                        holder.setText(R.id.duration, TimeUtils.formatVideoTime((long) item.getDuration()));
                        holder.setOnIntemClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View view) {
                                jumpVideoPlay(item.getActionUrl(), item.getTitle(), item.getId(), item.getDesc());
                            }
                        });
                    }
                };
            }
            binding.recyclerView.setLayoutManager(new LinearLayoutManager(this));
            binding.recyclerView.setAdapter(adapter);
        } else
            binding.tvHint.setVisibility(View.VISIBLE);
    }

    @Override
    public void onClick(View view) {
        int id = view.getId();
        if (id == R.id.back) {
            finish();
        } else if (id == R.id.clean_history) {
            if (mList.size() != 0) {
                //确认清除窗口
                showAlterDialog();
            } else
                ToastUtils.showShort("本来无一物,何处惹尘埃!");
        }
    }

    private void showAlterDialog() {
        final AlertDialog.Builder alterDiaglog = new AlertDialog.Builder(this);
        TextView title = new TextView(this);
        title.setText("删了就没了!");
        title.setPadding(10, 30, 10, 10);//边距
        title.setGravity(Gravity.CENTER);//位置
        title.setTextSize(23); //字体的大小
        alterDiaglog.setCustomTitle(title);//设置字体


        alterDiaglog.setPositiveButton("确定删除", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {

                DBManager dbManager = new DBManager(DownloadActivity.this);
                dbManager.delete("download");
                File appDir = new File(Environment.getExternalStorageDirectory(), DIR_DOWNLOAD);
                deleteFile(appDir);
                ToastUtils.showShort("已经删除");
                mList.clear();
                binding.tvHint.setVisibility(View.VISIBLE);
                adapter.notifyDataSetChanged();
            }
        });
        alterDiaglog.setNeutralButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {

            }
        });

        //显示
        alterDiaglog.show();
    }

    //flie：要删除的文件夹的所在位置
    private void deleteFile(File file) {
        if (file.isDirectory()) {
            File[] files = file.listFiles();
            for (int i = 0; i < files.length; i++) {
                File f = files[i];
                deleteFile(f);
            }
            file.delete();//如要保留文件夹，只删除文件，请注释这行
        } else if (file.exists()) {
            file.delete();
        }
    }
    private void jumpVideoPlay(String url, String title, String id, String desc) {
        ARouter.getInstance()
                .build(RouterActivityPath.EyeVideo.PAGER_PLAY)
                .withString("url", url)
                .withString("title", title)
                .withString("id", id)
                .withString("desc", desc)
                .navigation();
    }
}
